<template>
  <el-form :inline="true" :model="searchForm" class="form-inline">
    <el-form-item label="搜索商品">
      <el-input v-model="searchForm.searchInfo" placeholder="请输入您要搜索的内容" />
    </el-form-item>
    <el-form-item label="商品种类">
      <el-select v-model="searchForm.category" placeholder="请选择种类">
        <el-option v-for="item in goodsCategories" :label="item" :value="item" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getSearchGoodsListData">搜索</el-button>
    </el-form-item>
  </el-form>
  <el-table :data="newGoodsList" style="width: 100%" height="600px">
    <el-table-column label="索引" width="80">
      <template #default="scope"
        ><span>{{
          scope.$index + 1 + (pageData.count - 1) * pageData.limitNum
        }}</span></template
      >
    </el-table-column>
    <el-table-column prop="proname" label="商品名" />
    <el-table-column prop="brand" label="品牌" />
    <el-table-column label="图片">
      <template #default="scope">
        <img width="100" :src="scope.row.img1" />
      </template>
    </el-table-column>
    <el-table-column prop="originprice" label="原价" />
    <el-table-column prop="discount" label="折扣数" />
  </el-table>
  <el-pagination
    layout="prev, pager, next"
    v-model:current-page="pageData.count"
    v-model:page-size="pageData.limitNum"
    :total="searchGoodsList.length || 0"
    :style="{justifyContent: 'center'}"
  />
</template>
<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { getGoodsCategoryListApi, getSearchGoodsListDataApi } from "@/api/list.js";
// 搜索商品所需的搜索信息和分类
const searchForm = reactive({
  searchInfo: "",
  category: "",
});

const pageData = ref({
  // 控制列表页数的数据
  count: 1,
  // 控制一页展示多少商品的数据
  limitNum: 3,
});

// 提前准备的获取商品种类的数据
const goodsCategories = ref();

// 提前准备的获取商品列表的数据
const searchGoodsList = ref([]);

const getGoodsCategoryList = async () => {
  const res = await getGoodsCategoryListApi();
  goodsCategories.value = res.data;
  //   console.log(goodsCategories.value);
};

const getSearchGoodsListData = async () => {
  try {
    const res = await getSearchGoodsListDataApi({
      category: searchForm.category,
      search: searchForm.searchInfo,
    });
    //   console.log(res.data);
    searchGoodsList.value = res.data;
    console.log(JSON.parse(JSON.stringify(searchGoodsList.value)));
  } catch (error) {
    console.log(error);
  }
};

const newGoodsList = computed(() => {
  const listStart = (pageData.value.count - 1) * pageData.value.limitNum;
  return (
    JSON.parse(JSON.stringify(searchGoodsList.value)).slice(listStart, listStart + pageData.value.limitNum) || []
  );
});

onMounted(() => {
  getGoodsCategoryList();
  getSearchGoodsListData();
  // console.log(newGoodsList);
});
</script>
<style lang="scss"></style>
